import useRequest from "@/api/useRequest";

export class ocrController {

  static async ocrAndCheckLog(data: any, timeoutMs: number, progressModal: any,totalNum: any, finshNum: any): Promise<any> {
    try {
      // 发送任务提交请求
      const response = await useRequest({
        url: "/OCR/v",
        method: "post",
        data,
      });
      const taskId = response.data.result;
      let pollingInterval;
      let polling = true; // 添加一个轮询标志变量
      const pollTaskStatus = async () => {
        console.log('pollTaskStatus{}检查状态')
        try {
          if (!polling) {
            // 如果轮询被标志为停止，则返回 null
            return null;
          }
          // 发送任务状态检查请求
          const statusResponse = await useRequest({
            url: "/OCR/getOcrLog?taskId=" + taskId,
            method: "get",
          });
          const status = statusResponse.data.taskStatus;
          console.log("status", status);
          if (status === "NOT_START" || status === "SUBMITTED" || status === "IN_PROGRESS") {
            if(status === "IN_PROGRESS"){
              if(progressModal){
                progressModal.value = true
              }
              if(statusResponse.data.taskLog.totalNum){
                totalNum.value = statusResponse.data.taskLog.totalNum
                finshNum.value = statusResponse.data.taskLog.finishNum
              }
            }
            // 继续轮询
            await new Promise(resolve => setTimeout(resolve, 5000)); // 等待5秒
            return pollTaskStatus(); // 继续轮询
          } else {
            clearInterval(pollingInterval);
            if (status === "SUCCESS") {
              console.log(statusResponse);
              // 返回任务制作成功的结果
              return statusResponse.data;
            } else {
              // 返回任务制作失败的结果
              throw new Error("任务制作失败");
            }
          }
        } catch (error) {
          throw new Error("任务状态检查失败");
        }
      };

      // 使用 Promise.race 来同时等待任务完成和超时时间的先发生
      const result = await Promise.race([
        pollTaskStatus(),
        new Promise((_, reject) => {
          setTimeout(() => {
            clearInterval(pollingInterval)
            polling = false
            reject(new Error("任务超时"));
          }, timeoutMs);
        }),
      ]);
      console.log('result:{}',result)
      return result;
    } catch (error) {
      console.log(error);
      throw new Error("提交任务失败");
    }
  }


    static batchOcr(userFileId:string): Promise<any> {
        return useRequest({
            url: "/whisper/file?userFileId="+userFileId,
            method: "get"
        })
    }

    static ocr(userFileId:string): Promise<any> {
        return useRequest({
            url: "/OCR/ocr?userFileId="+userFileId,
            method: "get"
        })
    }
}
